package com.choudou5.solr.util;

import cn.hutool.core.util.NumberUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @name 配置工具类
 * @author choudou5
 * @date 2018-7-13
 */
public class ConfigUtil {

    private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class);

    public final static ResourceBundle resource = ResourceBundle.getBundle("conf/system");

    private static final Map<String, String> propCacheMap = new HashMap<>();

    public static String getStr(String key){
        String val = propCacheMap.get(key);
        if(val == null){
            val = resource.getString(key);
            if(val == null)
                throw new IllegalArgumentException("param "+key+" value is null");
            propCacheMap.put(key, val);
        }
        return val;
    }

    public static String getStr(String key, String def){
        try {
            return getStr(key);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ConfigUtil getStr '"+key+"' fail.", e);
            return def;
        }
    }

    public static int getInt(String key){
        String val = getStr(key);
        if(!NumberUtil.isNumber(val))
            throw new IllegalArgumentException("param "+key+" value not int type");
        return Integer.parseInt(val);
    }

    public static long getLong(String key){
        String val = getStr(key);
        if(!NumberUtil.isNumber(val))
            throw new IllegalArgumentException("param "+key+" value not long type");
        return Long.parseLong(val);
    }

    public static boolean getBool(String key){
        String val = getStr(key);
        return Boolean.parseBoolean(val);
    }

    /**
     * 系统模式
     * @return
     */
    public static String getSysMode(){
        return getStr("solr.mode", "standalone");
    }

    public static String getSolrHome(){
        return getStr("solr.home");
    }

    public static String[] getSolrIpWhiteList(){
        return StrUtil.splitToArray(getStr("solr.ip.whitelist"), ',');
    }

}
